'''
Author: Andy.Chow
Date: 2024-06-11 10:01:28
LastEditors: Andy.Chow
Description: 
执行命令格式如下: # 每个文件需空格间隔开
python CPPCheckTest.py 待检查文件1(含路径) 待检查文件1(含路径) ......
'''
import os
import subprocess
import re
import sys

def TIMEOUT_SHELL_COMMAND(command:str, timeout=60, capture_output=False, encoding ='utf8', cwd=None) -> list:
    cmd = command
    print('Process CMD START: [cmd={}] [timeout={}] [capture_out={}] [encoding={}] [cwd={}]'.format(
        cmd, timeout, capture_output, encoding, cwd))

    process = subprocess.run(cmd,
                             shell=True,
                             timeout=timeout,
                             capture_output=capture_output,
                             encoding=encoding,
                             cwd=cwd)
    print('Process CMD END: [returncode={}] [cmd={}] [timeout={}] [capture_out={}] [encoding={}] [cwd={}]'.format(
        process.returncode ,cmd, timeout, capture_output, encoding, cwd))
    if process.stdout:
        # LOG(LEVEL_INFO, 'CMD stdout = [{}]'.format(process.stdout))
        # if process.stderr:
        #   LOG(LEVEL_INFO, 'CMD stderr = [{}]'.format(process.stderr))
        if (not process.returncode):
            return [process.returncode, process.stdout.strip().split('\n')]
    else:
        return [process.returncode, []]

# _CPPCHECK_DIR = 'cppcheck/'
_CPPCHECK_TOOLS_PATH  = os.getcwd() + '/' + 'cppcheck/'
_CPPCHECK_RESULT_PATH = os.getcwd() + '/' + 'cppcheck_result_dir/'
def _Test_CPPCheck(filename_with_path:list):    
    print(f'*******_Test_CPPCheck:{filename_with_path}')
    try:
        if not os.path.exists(_CPPCHECK_RESULT_PATH):
            os.makedirs(_CPPCHECK_RESULT_PATH)
            print(f'make dir:{_CPPCHECK_RESULT_PATH}')
    except Exception as e:
        print(f"make dir error:{e}")
    cppcheck_script = _CPPCHECK_TOOLS_PATH +'cppcheck'
    reporthtml_script = _CPPCHECK_TOOLS_PATH + 'htmlreport/cppcheck-htmlreport'
    reporthtml_report_dir = "cppcheck_htmlresult_dir"
    reporthtml_report_path = _CPPCHECK_RESULT_PATH + reporthtml_report_dir + "/"
    cppcheck_outputfile = _CPPCHECK_RESULT_PATH + 'cppcheck_result.xml'
    cppcheck_path = ''
    cppcheck_file_filter = ''
    for fileinfo in filename_with_path:
        filepath = os.path.dirname(fileinfo)
        filename = os.path.basename(fileinfo)
        print(f'********cppcheck file path:{filepath}, file name:{filename}')
        cppcheck_path += filepath + '/ ' #'cppcheck/'
        cppcheck_file_filter += '--file-filter=' + fileinfo +' ' # 指定目录--file-filter=xxx/manu.c 或当前目录--file-filter=./manu.c'
    
    if cppcheck_file_filter:
        if os.path.exists(cppcheck_outputfile):
            cmd = 'rm %s' % (cppcheck_outputfile)
            TIMEOUT_SHELL_COMMAND(cmd)
    check_suppress = ""
    check_suppress += " " + "--suppress=missingInclude"
    check_suppress += " " + "--suppress=unusedFunction"
    check_suppress += " " + "--suppress=unmatchedSuppression"
    check_suppress += " " + "--suppress=unusedStructMember"
    check_suppress += " " + "--suppress=variableScope"
    check_suppress += " " + "--suppress=unreadVariable"
    check_suppress += " " + "--suppress=constParameter"
    check_suppress += " " + "--suppress=ConfigurationNotChecked"
    #-DUNITCODESECTION -DMARSHAL_COMMON_TYPES_TABLE -DLOGGING_PRESERVE_MESSAGE_ENUM
    check_suppress += '-DUNITCODESECTION -DMARSHAL_COMMON_TYPES_TABLE -DLOGGING_PRESERVE_MESSAGE_ENUM'
    check_suppress += " " + "--suppress=unknownMacro"
    check_suppress += " " + "--suppress=missingReturn"

    # cmd = '%s --force --enable=all %s  --xml --output-file=%s %s %s' % (
    #         cppcheck_script, check_suppress, cppcheck_outputfile, cppcheck_path, cppcheck_file_filter)
    cmd = f'{cppcheck_script} --force --enable=all {check_suppress} --xml --output-file={cppcheck_outputfile} {cppcheck_path} {cppcheck_file_filter}'

    TIMEOUT_SHELL_COMMAND(cmd, timeout=180)
    # run cppcheck cmd
    if os.path.exists(reporthtml_report_path):
        cmd = 'rm -rf %s' % (reporthtml_report_path)
    # cmd = '%s --file=%s --report-dir=%s --source-dir=.' % (
    #         reporthtml_script,
    #         cppcheck_outputfile,
    #         reporthtml_report_path.rstrip('/'))    
    cmd = f'{reporthtml_script} --file={cppcheck_outputfile} --report-dir={reporthtml_report_path} --source-dir=.'    
    TIMEOUT_SHELL_COMMAND(cmd, timeout=180)

_Need_CPPCheck_File = 'manu.c'

if __name__ == '__main__':
    cppcheck_files_with_path = sys.argv[1:]
    _Test_CPPCheck(cppcheck_files_with_path)